<template>
  <div class="editor-box" ref='editor'></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, ref, reactive } from 'vue'
import WangEditor from 'wangeditor'
import { MenuActive } from 'wangeditor/dist/menus/menu-constructors/Menu'
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'

const { $, BtnMenu } = WangEditor

// 第一，菜单 class ，Button 菜单继承 BtnMenu class
class HtmlMenu extends BtnMenu implements MenuActive {
  constructor(editor: WangEditor) {
  // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
    const $elem = $(
      `<div class="w-e-menu" data-title="html">
        <button>html</button>
      </div>`
    )
    super($elem, editor)
  }
  // 菜单点击事件
  clickHandler() {
    // 做任何你想做的事情
    // 可参考【常用 API】文档，来操作编辑器
    const panel = this.editor.$textContainerElem.elems[0]
    if (panel.children) {
      let status: boolean = false
      for (let i = 0; i < panel.children.length; i++) {
        const dom = panel.children[i]
        let classes: string | null = dom.getAttribute('class') ? dom.getAttribute('class') : ''
        if (classes && classes.indexOf('html-div') !== -1) {
          status = true
          this.unActive()
          this.editor.txt.html(panel.children[i].innerHTML)
          panel.children[i].remove()
          break
        }
      }

      if (!status) {
        this.active()
        const ele = document.createElement('div')
        ele.className = 'html-div'
        ele.style.position = 'absolute'
        ele.style.width = '100%'
        ele.style.height = '100%'
        ele.style.left = '0'
        ele.style.top = '0'
        ele.style.background = '#fff'
        ele.style.padding = '10px'
        ele.style.overflowY = 'auto'
        ele.setAttribute('contenteditable', 'true')
        ele.innerHTML = hljs.highlight(this.editor.$textElem.elems[0].innerHTML, {language: 'html'}).value
        this.editor.$textContainerElem.elems[0].append(ele)
      }
    }

  }

  // 菜单是否被激活（如果不需要，这个函数可以空着）
  // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
  // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
  tryChangeActive() {
    console.log()
  }
}

WangEditor.registerMenu('HtmlMenu', HtmlMenu)

interface Props {
  content?: string
}

const props = withDefaults(defineProps<Props>(), {
  content: ''
})

const emit = defineEmits(['change'])

const editor = ref()
let instance: WangEditor | null
onMounted(() => {
  instance = new WangEditor(editor.value)
  Object.assign(instance.config, {
    pasteFilterStyle: false,
    customUploadImg(resultFiles: any, insertImgFn: Function) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      const imgUrl = ''
      // 上传图片，返回结果，将图片插入到编辑器中
      insertImgFn(imgUrl)
    },
    onchange(e: any) {
      console.log('change')
      emit('change', e)
    },
  })
  instance.create()
  instance.txt.html(props.content)
})
onBeforeUnmount(() => {
  instance?.destroy()
  instance = null
})

</script>

<style scoped>
.editor-box {
  margin-top: 20px;
}
</style>